//
// Created by 86150 on 2021/11/18.
//
#include "caller.h"

caller::caller(std::string name, std::string ip, short port):
	user_name(name), goal_ip(ip), goal_port(port)
{
	if (WSAStartup(MAKEWORD(2, 1), &wsadata) != 0)
		error("initial fail!");

	goal_sock = socket(PF_INET, SOCK_STREAM, 0);
	if(goal_sock == INVALID_SOCKET)
		error("socket invaild!");

	memset(&goal_sock_addr, 0, sizeof(goal_sock_addr));
	goal_sock_addr.sin_family = AF_INET;
	goal_sock_addr.sin_addr.s_addr = inet_addr(goal_ip.c_str());
	goal_sock_addr.sin_port = htons(goal_port);
}
void caller::connect_chatroom_test()
{
	if (connect(goal_sock, (SOCKADDR*)&goal_sock_addr,sizeof(goal_sock_addr)) == SOCKET_ERROR)
		error("connect fail!");
	send(goal_sock, ("<chat>" + user_name).c_str(), 20, 0);

	std::thread reader([this] () {
		char buf[100];

		while (recv(goal_sock, buf, sizeof(buf) +  - 1, 0) != 0)
			std::cout<<std::string(buf)<<"\n";
	});

	std::thread writer([this] () {
		char buf[100];

		while(true) {
			std::cin>>buf;
			send(goal_sock, buf, sizeof(buf) - 1, 0);
		}
	});

	reader.join();
	writer.join();
}
void caller::error(std::string info)
{
	std::cout<<"Error: " + info + "\n";
	exit(-1);
}
caller::~caller()
{
	closesocket(goal_sock);
	WSACleanup();
}


